package com.wangzhenyu.learn.test.android_.fragmentViewModel

import android.app.Application
import androidx.lifecycle.*
import com.wangzhenyu.common.base.BaseApplication
import com.wangzhenyu.common.util.log.LogUtil
import com.wangzhenyu.learn.test.jetpack.room_.InstanceRoom
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class RoomTestFragmentViewModel(application: Application) : AndroidViewModel(application) {

    val storeName: MutableLiveData<String> = MutableLiveData()

    val storeData: LiveData<List<InstanceRoom.StoreTypeName>> =
        Transformations.switchMap(storeName) { name ->
            getStoreDao().queryStoreTypeName(name)
        }

    private fun getStoreDao(): InstanceRoom.StoreDao {
        return InstanceRoom.TestDatabase.getInstance(BaseApplication.myApplication).getStoreDao()
    }

    fun insertStore(vararg word: InstanceRoom.Store) {
        viewModelScope.launch(Dispatchers.IO) {
            val result = getStoreDao().addStore(*word)
            LogUtil.default01(result.toString())
        }
    }

    fun insertMaster(vararg master: InstanceRoom.Master) {
        viewModelScope.launch(Dispatchers.IO) {
            getStoreDao().addMaster(*master)
        }
    }

    fun updateStore(vararg store: InstanceRoom.Store) {
        viewModelScope.launch(Dispatchers.IO) {
            val result = getStoreDao().updateStore(*store)
            LogUtil.default01(result.toString())
        }
    }

    fun deleteStore(vararg store: InstanceRoom.Store) {
        viewModelScope.launch(Dispatchers.IO) {
            val result = getStoreDao().deleteStore(*store)
            LogUtil.default01(result.toString())
        }
    }

    //查询Store与与其对应的Master
    fun queryStoreAndMaster(name: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val result = getStoreDao().queryStoreMaster(name)
            for (i in result) {
                LogUtil.default01(i.store.toString())
                LogUtil.default01(i.master.toString())
            }

        }
    }


}